using Project.ViewModels;
using Project.Views.Abstractions;
using UnityEngine;
using UnityEngine.UI;

namespace Project.Views
{
    public class RootScreenView : DisposableViewBase
    {
        private RootScreenViewModel _rootScreenViewModel;

        [SerializeField] private HelpPanelView _helpPanelView;
        [SerializeField] private CharacterStatsPanelView _characterStatsPanelView;
        [Space]
        [SerializeField] private Button _helpButton;

        public void Initialize(RootScreenViewModel rootScreenViewModel)
        {
            _rootScreenViewModel = rootScreenViewModel;

            _helpPanelView.Initialize();
            _characterStatsPanelView.Initialize(_rootScreenViewModel.CharacterStatsPanelViewModel.Value);

            OnIsHelpPanelShownValueChanged(_rootScreenViewModel.IsHelpPanelShown.Value);
            OnIsCharacterStatsPanelShownValueChanged(_rootScreenViewModel.IsCharacterStatsPanelShown.Value);
            OnCharacterStatsPanelViewModelValueChanged(_rootScreenViewModel.CharacterStatsPanelViewModel.Value);

            Subscribe();
        }

        protected override void Subscribe()
        {
            _rootScreenViewModel.IsHelpPanelShown.ValueChanged += OnIsHelpPanelShownValueChanged;
            _rootScreenViewModel.IsCharacterStatsPanelShown.ValueChanged += OnIsCharacterStatsPanelShownValueChanged;
            _rootScreenViewModel.CharacterStatsPanelViewModel.ValueChanged += OnCharacterStatsPanelViewModelValueChanged;

            _helpButton.onClick.AddListener(_rootScreenViewModel.ToggleIsHelpPanelShown);
        }
        protected override void Unsubscribe()
        {
            _rootScreenViewModel.IsHelpPanelShown.ValueChanged -= OnIsHelpPanelShownValueChanged;
            _rootScreenViewModel.IsCharacterStatsPanelShown.ValueChanged -= OnIsCharacterStatsPanelShownValueChanged;
            _rootScreenViewModel.CharacterStatsPanelViewModel.ValueChanged -= OnCharacterStatsPanelViewModelValueChanged;

            _helpButton.onClick.RemoveListener(_rootScreenViewModel.ToggleIsHelpPanelShown);
        }

        private void OnIsHelpPanelShownValueChanged(bool newValue)
        {
            if (newValue)
                _helpPanelView.Show();
            else
                _helpPanelView.Hide();
        }
        private void OnIsCharacterStatsPanelShownValueChanged(bool newValue)
        {
            if (newValue)
                _characterStatsPanelView.Show();
            else
                _characterStatsPanelView.Hide();
        }
        private void OnCharacterStatsPanelViewModelValueChanged(CharacterStatsPanelViewModel newValue)
        {
            _characterStatsPanelView.SetViewModel(newValue);
        }
    }
}
